//
//  HCUserAccountViewModel.swift
//  Hweibome
//
//  Created by apple on 15/12/8.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit

//取消nsobject
class HCUserAccountViewModel {
    //ViewModel 引用Model(返着来不可以)
    var userAccount : HCUserAccount?

    //归档解档路径
    var archivePath:String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
    
    var userLogon:Bool{
        return accessToken != nil
    }
    var accessToken:String?{
        if let accessToken = userAccount?.access_token where !isExpires {
            return accessToken
        }
        return nil
    }
    
    var isExpires:Bool {
        guard let expiresDate = userAccount?.expiresDate else
        {
            return true
        }
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        return true
    
    }
    
    
    //单例,全局访问点
    static let sharedAccount:HCUserAccountViewModel = HCUserAccountViewModel()
    
    //构造方法私有化
    private init(){
        userAccount = loadUserAccount()
    }

}

//MARK: - OAuth 登陆请求
extension HCUserAccountViewModel
{
     func loadAccessToken(code: String, complete:(isSuccessed:Bool)->())
    {
        
        HCNetworkTools.shareTools.loadAccessToken(code){
            (response,error) -> () in
            if error != nil {
                printLog("请求错误：\(error)")
                complete(isSuccessed: false)
                return
            }
            guard let dict = response as? [String:AnyObject]else{
                printLog("返回数据不是字典")
                return
            }
            let account = HCUserAccount(dict: dict)
            
            self.userAccount = account
            
            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complete)
         }
    }
// 请求用户的数据
    
  private  func loadUserInfo(uid:String,accessToken:String,complete:(isSuccessed: Bool)->())
    {
        HCNetworkTools.shareTools.loadUserInfo(uid, accessToken: accessToken) { (response, error) -> () in
            if error != nil
            {
                printLog("请求失败\(error)")
                complete(isSuccessed: false)
                return
            }
          //  printLog(response)
            guard let responseDic = response as? [String:AnyObject] else {
                printLog("返回数据不是一个字典")
                return
            }
            
            self.userAccount?.screen_name = responseDic["screen_name"]as? String
            self.userAccount?.avatar_large = responseDic["avatar_large"]as? String

            self.saveAccount(self.userAccount!)
            complete(isSuccessed: true)
        }
    }

//    
    func saveAccount(account:HCUserAccount)
    {
        NSKeyedArchiver.archiveRootObject(account, toFile: archivePath)
    }
    
    func loadUserAccount() ->HCUserAccount?
    {
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? HCUserAccount
        return result
    }
}